<template>
  <transition name="fade">
    <n-button
      v-show="visible"
      circle
      size="large"
      type="primary"
      class="back-to-top"
      @click="scrollToTop"
      :title="'返回顶部'"
    >
      <template #icon>
        <n-icon :size="20">
          <ArrowUpOutline />
        </n-icon>
      </template>
    </n-button>
  </transition>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ArrowUpOutline } from '@vicons/ionicons5'

// 响应式状态
const visible = ref(false)

// 滚动处理函数
const handleScroll = () => {
  visible.value = window.scrollY > 300
}

// 返回顶部函数
const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  })
}

// 生命周期
onMounted(() => {
  window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped>
.back-to-top {
  position: fixed;
  bottom: 32px;
  right: 32px;
  z-index: 1000;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .back-to-top {
    bottom: 24px;
    right: 24px;
  }
}

/* 淡入淡出动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
